package com.dibang.app.operation.view.impl;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.dibang.app.R;
import com.dibang.app.adapter.MainPagerAdapter;
import com.dibang.app.mvp.abs.AbsView;
import com.dibang.app.mvp.util.DPUtil;
import com.dibang.app.mvp.util.PickerCity;
import com.dibang.app.mvp.util.WindowUtil;
import com.dibang.app.operation.control.abs.MainControl;
import com.dibang.app.operation.model.abs.MainModel;
import com.dibang.app.operation.presenter.abs.MainPresenter;
import com.dibang.app.operation.view.abs.MainView;
import com.dibang.app.ui.fragment.IssueGroupFragment;
import com.dibang.app.ui.fragment.PeerFragment;
import com.dibang.app.view.DiffuseWaveView;
import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yinglan.scrolllayout.ScrollLayout;

import java.util.ArrayList;
import java.util.Date;

import io.reactivex.functions.Consumer;

/**
 * Created by wxl on 2019/7/24.
 */

public class MainViewImpl extends AbsView<MainControl, MainView, MainPresenter, MainModel> implements MainView {


    private AMapLocationClient client;

    @Override
    public void onUpScrollLayoutChangedWaveViewExpand(@NonNull ScrollLayout mScrollLayout, @NonNull DiffuseWaveView diffuseWaveView) {
        mScrollLayout.setOnScrollChangedListener(new ScrollLayout.OnScrollChangedListener() {
            @Override
            public void onScrollProgressChanged(float currentProgress) {
                if (currentProgress >= 0) {
                    float precent = 255 * currentProgress;
                    if (precent > 255) {
                        precent = 255;
                    } else if (precent < 0) {
                        precent = 0;
                    }
                    mScrollLayout.getBackground().setAlpha(255 - (int) precent);
                    if (currentProgress <= 0.005) {
                        diffuseWaveView.open();
                    } else {
                        diffuseWaveView.close();
                    }
                }
            }

            @Override
            public void onScrollFinished(ScrollLayout.Status currentStatus) {

            }

            @Override
            public void onChildScroll(int top) {

            }
        });
        mScrollLayout.getBackground().setAlpha(0);
        diffuseWaveView.setX(DPUtil.dip2px(mScrollLayout.getContext(), 85));
    }


    @Override
    public void onMapViewExpand(@NonNull TextureMapView mapView, Marker marker) {
        AMap aMap = mapView.getMap();
        onGetLocationPermissions((FragmentActivity) mapView.getContext(), new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    aMap.setMyLocationStyle(presenter.generateLocationStyle(mapView.getContext()));
                    // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
                    aMap.setMyLocationEnabled(true);
                    setAMapUiSetting(aMap);
                    aMap.showIndoorMap(false);
                    aMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                                    new LatLng(39.92463, 116.389139), //经纬度
                                    14, //缩放级别 3 -19 3：最大视角，看到全中国，19：最小级别，看到细节
                                    30, //视角从垂直于地面，向下倾斜60度，此时与地面夹角是30度
                                    90) //地图顺时针旋转90度
                            )
                    );
                    client = presenter.generateLocationClient(mapView.getContext());
                    setOnAMapLocationClientListener(mapView, aMap, marker, client);
                    client.startLocation();
                }
            }
        });
    }


    /**
     * 申请定位权限
     *
     * @param activity
     * @param onNext
     */
    @SuppressLint("CheckResult")
    private void onGetLocationPermissions(FragmentActivity activity, Consumer<Boolean> onNext) {
        new RxPermissions(activity)
                .request(Manifest.permission.ACCESS_FINE_LOCATION)//这里填写所需要的权限多个的话可以逗号隔开
                .subscribe(onNext);
    }

    @Override
    public void onViewPagerExpand(@NonNull FragmentManager fm, @NonNull ViewPager viewPager) {
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(PeerFragment.newInstance());
        fragments.add(IssueGroupFragment.newInstance());
        viewPager.setAdapter(new MainPagerAdapter(fm, fragments));
        int height = WindowUtil.getScreenHeight(viewPager.getContext())
                - ImmersionBar.getStatusBarHeight((Activity) viewPager.getContext())
                - DPUtil.dip2px(viewPager.getContext(), 230);
        viewPager.getLayoutParams().height = height;
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                control.onPagerSelectChanged(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    @Override
    public void onPeerTabSelectChanged(boolean isOpen, int peerPointer, @NonNull View targetView) {
        RelativeLayout peerLayout = targetView.findViewById(R.id.main_peer_line_layout);
        TextView peerText = targetView.findViewById(R.id.main_peer_line_text);
        View peerIndicator = targetView.findViewById(R.id.main_peer_line_divider);
        RelativeLayout groupLayout = targetView.findViewById(R.id.main_peer_group_layout);
        TextView groupText = targetView.findViewById(R.id.main_peer_group_text);
        View groupIndicator = targetView.findViewById(R.id.main_peer_group_divider);
        if (peerPointer == 0) {
            peerLayout.setBackgroundResource(isOpen ? R.drawable.shape_normal_white_bg : R.drawable.shape_gray_brold_radiu5_bg);
            peerText.setTextColor(ContextCompat.getColor(targetView.getContext(), R.color.blue_gradient_end_color));
            peerIndicator.setVisibility(isOpen ? View.VISIBLE : View.GONE);
            groupLayout.setBackgroundResource(R.drawable.shape_normal_white_bg);
            groupText.setTextColor(ContextCompat.getColor(targetView.getContext(), R.color.gray_text_color));
            groupIndicator.setVisibility(View.GONE);
        } else {
            groupLayout.setBackgroundResource(isOpen ? R.drawable.shape_normal_white_bg : R.drawable.shape_gray_brold_radiu5_bg);
            groupText.setTextColor(ContextCompat.getColor(targetView.getContext(), R.color.blue_gradient_end_color));
            groupIndicator.setVisibility(isOpen ? View.VISIBLE : View.GONE);
            peerLayout.setBackgroundResource(R.drawable.shape_normal_white_bg);
            peerText.setTextColor(ContextCompat.getColor(targetView.getContext(), R.color.gray_text_color));
            peerIndicator.setVisibility(View.GONE);
        }
    }


    @Override
    public void reloadLocation() {
        if (client != null) {
            Log.d("loc","reloadLocation");
            client.startLocation();
        }
    }

    @Override
    public void onSelectStartTime(@NonNull Context context) {
        DatePickDialog dialog = new DatePickDialog(context);
        //设置上下年分限制
        dialog.setYearLimt(5);
        //设置标题
        dialog.setTitle("选择出发时间");
        //设置类型
        dialog.setType(DateType.TYPE_ALL);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd HH:mm");
        //设置选择回调
        dialog.setOnChangeLisener(null);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(new OnSureLisener() {
            @Override
            public void onSure(Date date) {
                control.onSelectedStartTimeChanged(date);
            }
        });
        dialog.show();
    }

    @Override
    public void onSelectCurrentCity(@NonNull FragmentActivity act) {
        PickerCity.getInstance().setActivity(act).setListener(city -> {
            control.onSelectedCurrentCityChanged(city);
        }).show();
    }



    /**
     * 设置定位监听
     *
     * @param aMap
     * @param client
     */
    private void setOnAMapLocationClientListener(@NonNull TextureMapView mapView, @NonNull AMap aMap, Marker marker, @NonNull AMapLocationClient client) {
        client.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                onAMapLocationChanged(mapView.getContext(), aMap, client, marker, aMapLocation);
            }
        });
    }


    /**
     * 定位回调
     *
     * @param context
     * @param aMap
     * @param marker
     * @param aMapLocation
     */
    private void onAMapLocationChanged(@NonNull Context context, @NonNull AMap aMap, @NonNull AMapLocationClient client, Marker marker, AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                client.stopLocation();
                if (marker != null) {
                    marker.destroy();
                }
                aMap.clear();
                marker = aMap.addMarker(makeMarkerOptions(context, aMapLocation));
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(latLng);
                aMap.moveCamera(cameraUpdate);
                control.onLocationChanged(aMapLocation);
            } else {
                control.onLocationFailed();
            }
        }
    }


    /**
     * 生成一个MarkerOptions
     *
     * @return
     */
    private MarkerOptions makeMarkerOptions(@NonNull Context context, @NonNull AMapLocation aMapLocation) {
        View view = render(aMapLocation, context);
        return new MarkerOptions()
                .infoWindowEnable(false)
                .position(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()))
                .period(2000).title(aMapLocation.getCity()).snippet(aMapLocation.getAoiName())
                .zIndex(16)
                .icon(BitmapDescriptorFactory.fromView(view));
    }


    /**
     * 自定义infowinfow窗口，将自定义的infoWindow和Marker关联起来
     */
    private View render(@NonNull AMapLocation aMapLocation, @NonNull Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.map_marker_window_layout, null);
        String snippet = aMapLocation.getAoiName();
        TextView snippetUi = view.findViewById(R.id.map_marker_window_adr_text);
        snippetUi.setText(snippet);
        return view;
    }


    /**
     * 设置AMapUiSetting
     *
     * @param aMap
     */
    private void setAMapUiSetting(@NonNull AMap aMap) {
        UiSettings uiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        uiSettings.setScaleControlsEnabled(true);//控制比例尺控件是否显示
        uiSettings.setZoomGesturesEnabled(true);
        uiSettings.setTiltGesturesEnabled(true);
        uiSettings.setRotateGesturesEnabled(true);
        uiSettings.setAllGesturesEnabled(true);
    }
}
